<?php
namespace Models;

/**
 *
 * @author Eugene Baranov <evgeny@baranov.eu>
 *
 */
class Photo extends Base {
    const ICON_SIZE = 130;
    const SLIDER_SIZE = 480;
    const MIN_SIZE = 0;
    const MAX_SIZE = -1;

    protected $object_id;
    protected $position;
    protected $owner;
    protected $caption;
    protected $link;
    protected $images;
    protected $album_object_id;

    public function toArray() {
        return array_merge(parent::toArray(), array(
            'object_id' => $this->object_id,
            'position' => $this->position,
            'owner' => $this->owner,
            'caption' => $this->caption,
            'link' => $this->link,
            'images' => json_encode($this->images),
            'album_object_id' => $this->album_object_id,
            'updated' => $this->updated,
            'created' => $this->created,
        ));
    }

    public function fromArray(array $data) {
        if (empty($data['images'])) {
            $data['images'] = array();
        } else {
            if (is_string($data['images'])) {
                $data['images'] = json_decode($data['images']);
            }
        }

        return parent::fromArray($data);
    }

    public function getId() {
        return $this->object_id;
    }

    public function getImage($size = self::MAX_SIZE) {
        if ($size == self::MIN_SIZE) {
            return array_pop($this->images);
        }

        if ($size == self::MAX_SIZE) {
            return array_shift($this->images);
        }

        foreach ($this->images as $i) {
            if ($i->width <= $size && $i->height <= $size) {
                return $i;
            }
        }
        return null;
    }

    public function getIcon() {
        return $this->getImage(self::ICON_SIZE);
    }

    public function getCaption() {
        return $this->caption;
    }
}